import { useActionState } from "react";
import { useFormStatus } from "react-dom"
// 表单处理函数
async function submitForm(prevState, formData) {
  // prevState: 之前的状态
  // formData: 表单数据

  const name = formData.get("name");
  const email = formData.get("email");

  // 模拟验证
  if (!name || !email) {
    return {
      success: false,
      message: "所有字段都是必填的",
    };
  }

  // 模拟 API 调用
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 这里通常是保存到数据库的操作
    console.log("保存数据:", { name, email });

    return {
      success: true,
      message: "表单提交成功！",
    };
  } catch (error) {
    return {
      success: false,
      message: "提交失败，请重试",
    };
  }
}

function ContactForm() {
  const [state, formAction, isPending] = useActionState(submitForm, null);

  return (
    <form action={formAction}>
      <div>
        <label htmlFor="name">姓名:</label>
        <input type="text" id="name" name="name" />
      </div>

      <div>
        <label htmlFor="email">邮箱:</label>
        <input type="email" id="email" name="email" />
      </div>

      <button type="submit" disabled={isPending}>
        {isPending ? "提交中..." : "提交"}
      </button>

      <MyFormStatus />

      {state && (
        <div
          style={{
            color: state.success ? "green" : "red",
            marginTop: "10px",
          }}
        >
          {state.message}
        </div>
      )}
    </form>
  );
}

function MyFormStatus() {
  const formStatus = useFormStatus()
  const { pending, data, method, action} = formStatus
  console.log(formStatus)
  return (
    <div>
      提交状态：{pending ? 'Submitting...' : 'Submitted'}
    </div>
  )
}

export default ContactForm